//index.js
//获取应用实例
const app = getApp();
var QQMapWX = require('../../qqmap-wx-jssdk.min.js');
var qqmapsdk;

Page({
  data: {
    // isPower: true,
    isDuaration:true,
    isMain: true,
    isShowList: true,
    isnoneList: false,
    isNums:null,
    index: null,
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    region: [],
    cardCur: 0,
    swiperList: '',
    text: '欢迎来到星房惠，在这里你可以找到想要的房源',
    picker: [],
    showcity: [],
    cityCode: '',
    hotnewsList: '', //热点资讯
    houseList: '', //楼盘列表
    loadModal: false,
    flag: false,
    current: 0,
    swiperCurrent: 0,
    popAdv: null, // 广告图片
  },
  // 点击跳转双11
  toDouble(){
    wx.navigateTo({
      url: '/pages/double/double',
    })
  },
  //事件处理函数
  RegionChange: function(e) {
    this.setData({
      region: e.detail.value
    })
  },
  onShow: function() {
    console.log(getApp().globalData)
    this.getAdvert()
    console.log('打开定位')
    let cityCode = wx.getStorageSync('cityCode')
    if (cityCode == '' || cityCode == undefined) {
      this.getUserLocation()
    }

    let adv = wx.getStorageSync('index.adv')
    let time = new Date().getTime()
    if (!adv || adv < time) {
      this.adv();
    }

  },
  preview(e) {
    let imglist = this.data.swiperList
    let arr = []
    imglist.map(item => {
      arr.push(item.photo_url)
    })
    wx.previewImage({
      urls: arr,
      current: arr[e.currentTarget.dataset.url]
    });
  },
  searchlist(e) {
    this.setData({
      searchvalue: e.detail.value
    })

  },
  searchdesc() {
    var that = this;
    var setid = app.globalData.cityCode;
    var searchvalue = that.data.searchvalue;
    if (searchvalue == '') {
      wx.showToast({
        title: '请输入内容',
        duration: 1000,
        icon: 'none'
      })
    } else {
      wx.showLoading({
        title: '加载中',

      })
      app.core('get', 'search_loupan_by_name/site_id/' + setid + '', {
        project_name: searchvalue
      }, (res) => {
        console.log(res)
        if (res.data.houses == '' && res.data.oldhouses == '') {
          wx.showToast({
            title: '暂无相关信息',
            duration: 1000,
            icon: 'none'
          })
        } else {
          wx.navigateTo({
            url: '/pages/loupan/searchlist?content=' + searchvalue + '',
          })
        }
        wx.hideLoading()
      })
    }

  },

  getUserLocation: function() {
    wx.getSetting({
      success: (res) => {
        // console.log(res)
        var vm = this;
        // console.log(JSON.stringify(res))
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置,确保您的定位已打开',
            content: '需要获取您的地理位置，请确认授权',
            success: function(res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 2000
                })

                vm.setData({
                  region: ['安徽省', '合肥', '蜀山区'], // 不存在匹配城市的时候，左上角定位默认显示合肥
                });

                // 不存在匹配城市的时候，默认显示合肥的 推荐楼盘、广告、热点资讯
                vm.hotNews("340100");
                vm.getAdvert("340100");
                vm.houseList("340100");
                console.log('拒绝定位')
              } else if (res.confirm) {
                wx.openSetting({
                  success: function(dataAu) {
                    // console.log(dataAu)
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //重新授权位置
                      wx.getLocation({
                        type: 'wgs84',
                        success(res) {
                          console.log(res)
                          const latitude = res.latitude
                          const longitude = res.longitude
                          const speed = res.speed
                          const accuracy = res.accuracy
                          vm.getLocal(latitude, longitude)
                          vm.setData({
                            isMain: true,
                            isPower: false,
                          });
                        },
                        fail(err) {
                          vm.setData({
                            region: ['安徽省', '合肥', '蜀山区'], // 不存在匹配城市的时候，左上角定位默认显示合肥
                          });

                          // 不存在匹配城市的时候，默认显示合肥的 推荐楼盘、广告、热点资讯
                          vm.hotNews("340100");
                          vm.getAdvert("340100");
                          vm.houseList("340100");
                        }
                      });
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
         }
       // else if (res.authSetting['scope.userLocation'] == undefined) {
        //   //调用wx.getLocation的API
        // }
        else {
          //调用wx.getLocation的API
          wx.getLocation({
            type: 'wgs84',
            success(res) {
              const latitude = res.latitude
              const longitude = res.longitude
              const speed = res.speed
              const accuracy = res.accuracy
              vm.getLocal(latitude, longitude)
              vm.setData({
                isMain: true,
                isPower: false,
              });
              console.log('定位成功')
            },
            fail(err) {
              vm.setData({
                region: ['安徽省', '合肥', '蜀山区'], // 不存在匹配城市的时候，左上角定位默认显示合肥
              });
              console.log('定位失败')
              console.log(err)
              // 不存在匹配城市的时候，默认显示合肥的 推荐楼盘、广告、热点资讯
              vm.hotNews("340100");
              vm.getAdvert("340100");
              vm.houseList("340100");
            }
          });
        }
      }
    })
  },
  // swiperChange: function (e) {
  //   this.setData({
  //     swiperCurrent: e.detail.current
  //   })
  // },
  onLoad: function() {
    // this.getAdvert();
    var key = true;
    wx.setStorageSync('citykey', key)
    qqmapsdk = new QQMapWX({
      key: 'XM4BZ-R5BHX-FIA4V-ZFFFN-QKEXO-3CFSP' //这里自己的key秘钥进行填充
    });
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true,
        isMain: true,
        isPower: false,
      });
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true,
          isMain: true,
          isPower: false,
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true,
            isMain: true,
            isPower: false,
          })
        }
      })
    };
    this.getCity();
    this.getUserLocation();
    // this.run1();
    setTimeout(() => {
      this.setData({
        isDuaration:false
      })
    },1000)
  },
  getUserInfo: function(e) {
    var vm = this;
    app.globalData.userInfo = e.detail.userInfo;
    if (e.detail.userInfo) {
      this.setData({
        userInfo: e.detail.userInfo,
        hasUserInfo: true,
        isMain: false,
        flag: true,
        isPower: true,
      });
      wx.getLocation({
        type: 'wgs84',
        success(res) {
          const latitude = res.latitude
          const longitude = res.longitude
          const speed = res.speed
          const accuracy = res.accuracy
          vm.getLocal(latitude, longitude)
        },
        fail(err) {
          vm.setData({
            region: ['安徽省', '合肥', '蜀山区'], // 不存在匹配城市的时候，左上角定位默认显示合肥
          });

          // 不存在匹配城市的时候，默认显示合肥的 推荐楼盘、广告、热点资讯
          vm.hotNews("340100");
          vm.getAdvert("340100");
          vm.houseList("340100");
        }
      });
    }


    //用户授权之后获取Code
    // wx.login({
    //   success(res) {
    //     console.log('获取code');
    //     if (res.code) {
    //       console.log("第二次：" + 1111);
    //       // 发起网络请求
    //       var userCode = res.code;
    //       wx.setStorageSync('js_code', userCode);
    //       console.log(res);
    //       console.log('userCode:--' + userCode);
    //       //用户授权之后---获取用户信息存入数据库
    //       console.log('** user-info **');
    //       // console.log(app.globalData.userInfo);
    //       var UserInfo = app.globalData.userInfo;
    //       var opid = wx.getStorageSync('user_new')
    //       // wx.showLoading({
    //       // 	title: '加载中',
    //       // })
    //       app.core('post', 'create_xcx_user', {
    //           'open_id': opid,
    //           'nickname': UserInfo.nickName,
    //           'headpic': UserInfo.avatarUrl,
    //           'js_code': userCode
    //         }, (res) => {
    //           console.log('存库成功');
    //           console.log('session_key:' + res.sessionKey);
    //           wx.setStorageSync('session_key', res.sessionKey);
    //           console.log("opid" + res.data.open_id);
    //           app.globalData.openid = res.data.open_id //用户openid  存全局
    //           console.log(res);
    //           wx.hideLoading()
    //         },
    //         (err) => {
    //           console.log(err)
    //         }
    //       )

    //     } else {
    //       console.log('登录失败！' + res.errMsg)
    //     }
    //   }
    // });
  },

  //获取用户当前位置
  getLocal: function(latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function(res) {
        console.log(res);
        let province = res.result.ad_info.province
        let city = res.result.ad_info.city.split("市", 1)
        console.log(city)
        let area = res.result.ad_info.district
        vm.setData({
          region: [province, city, area] //赋值当前位置信息
        });

        //拿到定位当前的位置与后台给的站点匹配，没有的话默认显示合肥340100
        console.log(vm.data.region)
        var crrentCity = vm.data.region[1][0];
        //获取后台给的匹配城市
        // wx.showLoading({
        // 	title: '加载中',
        // })
        app.core('get', 'get_all_sites', {
            // data 部分
          }, (res) => {
            // wx.hideLoading()
            console.log(res)
            var newList = [];
            for (var k = 0; k < res.data.length; k++) {
              newList.push(res.data[k].area)
            }
            var ifHave = newList.indexOf(crrentCity); //查找当前的城市是否在匹配的城市下，不存在返回 -1， 存在返回当前的索引
            if (ifHave == -1) {
              vm.setData({
                region: [province, '合肥', area] // 不存在匹配城市的时候，左上角定位默认显示合肥
              });

              // 不存在匹配城市的时候，默认显示合肥的 推荐楼盘、广告、热点资讯
              vm.hotNews("340100");
              vm.getAdvert("340100");
              vm.houseList("340100");
            } else {
              // 找到匹配城市的时候，显示对应城市的 推荐楼盘、广告、热点资讯
              var hasCity = vm.data.region[1][0];
              // console.log('找到了对应的城市并打印出来');
              var cityCode = res.data[ifHave].id; //根据当前的数组索引找到对应的值，res.data服务端的返回list
              wx.setStorageSync('cityCode', cityCode)
              app.globalData.cityCode = cityCode
              console.log(cityCode)
              vm.hotNews(cityCode);
              vm.getAdvert(cityCode);
              vm.houseList(cityCode);
            }
          },
          (err) => {
            console.log(err)
          }
        )
      },
      fail: function(res) {
        console.log('取消');
      },
      complete: function(res) {
        // console.log(res);
      }
    });
  },

  DotStyle(e) {
    this.setData({
      DotStyle: e.detail.value
    })
  },
  cardSwiper(e) {
    this.setData({
      swiperCurrent: e.detail.current
    })
  },

  //跳转
  navigateTotab: function(e) {
    // console.log(e);
    var toUrl = e.currentTarget.dataset.url;
    // console.log(toUrl);
    wx.switchTab({
      url: toUrl
    });
  },
  navigateTo: function(e) {
    // console.log(e);
    var toUrl = e.currentTarget.dataset.url;
    // console.log(toUrl);
    wx.navigateTo({
      url: toUrl
    });
  },

  gotoList: function(e) {
    wx.switchTab({
      url: e.currentTarget.dataset.url
    });
  },

  gotohouseList: function(e) {
    wx.switchTab({
      url: e.currentTarget.dataset.url
    });
  },

  //获取城市
  getCity: function() {
    // wx.showLoading({
    //   title: '加载中',
    // })
    // 获取城市
    var vm = this;
    app.core('get', 'get_all_sites', {
        // data 部分
      }, (res) => {
        // wx.showLoading({
        // 	            title: '加载中',
        //           })

        console.log(res,'res2323')
        var picker = vm.data.picker;
        var citylist = [];
        var showcitylist = [];
        for (var i = 0; i < res.data.length; i++) {
          citylist.push({
            name: res.data[i].area,
            id: res.data[i].id
          });
          showcitylist.push(res.data[i].area);
        }
        vm.setData({
          picker: citylist,
          showcityCode: showcitylist
        });
        // wx.hideLoading()
      },
      (err) => {
        console.log(err)
      }
    )
  },

  //选择城市
  PickerChange(e) {
    console.log(e);
    var vm = this;
    var picker = vm.data.picker;
    var cityCode = vm.data.cityCode;
    for (var j = 0; j < picker.length; j++) {
      if (j == e.detail.value) {
        vm.setData({
          cityCode: picker[j].id,
          index: e.detail.value
        });
        app.globalData.cityCode = picker[j].id; // 修改全部变量 cityCode， 后面进入页面获取城市code用
        wx.setStorageSync('cityCode', picker[j].id)
        console.log(app.globalData.cityCode)
        vm.setData({
          loadModal: true
        })
        setTimeout(function() {
          vm.setData({
            loadModal: false
          })
        }, 1500)

        //切换城市获取对应的数据
        vm.getAdvert(picker[j].id); //广告获取
        vm.hotNews(picker[j].id); //热点资讯
        vm.houseList(picker[j].id); //推荐楼盘列表
        var key = true;
        wx.setStorageSync('citykey', key)
      }
    }
  },

  //广告获取
  getAdvert: function(cityCode) {
    var vm = this;
    var isNumsList=null;
    let setid = cityCode || wx.getStorageSync('cityCode')
    app.core('get', 'get_banner_advert/site_id/' + setid + '','', (res) => {
        // console.log(res);
        vm.setData({
          swiperList: res.data,
        });
      },
      (err) => {
        console.log(err)
      }
    )
  },
  //热点资讯
  hotNews: function(cityCode) {
    var vm = this;
    // wx.showLoading({
    //   title: '加载中',
    // })
    app.core('get', 'get_home_hot_news/site_id/' + cityCode, {
        // data 部分
      }, (res) => {
        var hotnewsList = vm.data.hotnewsList;
        vm.setData({
          hotnewsList: res.data
        })
        // wx.hideLoading()
      },
      (err) => {
        console.log(err)
      }
    )

  },
  //进入热点资讯 详情
  gethotDesc: function(e) {
    console.log(e);
    var id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/information/detail?id='+ id,
    })
  },

  //推荐楼盘列表
  houseList: function(cityCode) {
    var vm = this;
    // wx.showLoading({
    //   title: '加载中',
    // })
    app.core('get', 'get_hot_houses/site_id/' + cityCode, {
        // data 部分
      }, (res) => {
        // console.log(res);
        var houseList = vm.data.houseList;
        vm.setData({
          houseList: res.data
        })
        // wx.hideLoading()
      },
      (err) => {
        console.log(err)
      }
    )
  },

  //楼盘搜索
  loupanSearch: function(e) {
    var cityCode = app.globalData.cityCode; //全局动态获取当前的城市id
    var vm = this;
    var currentVal = (e.detail.value).replace(/\s+/g, ''); //当前输入的关键字
    if (currentVal == '') {
      wx.showToast({
        title: '请输入有效查询条件',
        duration: 2000,
        icon: 'none'
      });
      vm.setData({
        isShowList: true,
        isnoneList: false
      });
      vm.houseList(cityCode);
      return;
    }
    app.core('get', 'search_tj_by_name/site_id/' + cityCode, {
        keywords: currentVal
      }, (res) => {
        console.log('搜索返回');
        console.log(res);

        if (res.resultCode == 200) {
          console.log(res.data.length);
          if (res.data.length > 0) {
            vm.setData({
              isShowList: true,
              isnoneList: false
            });
            wx.showLoading({
              title: '努力加载中...',
            });
            setTimeout(function() {
              wx.hideLoading();
              vm.setData({
                houseList: res.data
              })
            }, 3000);

          } else {
            vm.setData({
              isShowList: false,
              isnoneList: true
            });
          }
        }
      },
      (err) => {
        console.log(err)
      }
    )

  },
  onShareAppMessage: function() {
    var that = this;
    var id = that.data.id
    var title = that.data.detail.title;　　 // 设置菜单中的转发按钮触发转发事件时的转发内容
    var imgurl = that.data.detail.photoUrl;
    return {
      title: title, // 默认是小程序的名称(可以写slogan等)
      path: 'pages/index/index',
      imageUrl: imgurl, //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
      success: function(res) {　　　　　　 // 转发成功之后的回调

        if (res.errMsg == 'shareAppMessage:ok') {
          wx.showToast({
            title: '转发成功',
            icon: 'none',
            duration: 1000
          })
        }
      },
      fail: function() {　　　　　　 // 转发失败之后的回调

        if (res.errMsg == 'shareAppMessage:fail cancel') {　　　　　　　　 // 用户取消转发
          wx.showToast({
            title: '已取消转发',
            icon: 'none',
            duration: 1000
          })
        } else if (res.errMsg == 'shareAppMessage:fail') {　　　　　　　　 // 转发失败，其中 detail message 为详细失败信息
          wx.showToast({
            title: '转发失败',
            icon: 'none',
            duration: 1000
          })
        }
      },
    }
  },
  getPhoneNumber: function(e) {
    console.log(e);
    // console.log(wx.getStorageSync('user_new'));
    console.log(e.detail.errMsg == "getPhoneNumber:ok");
    var data = {};
    data.iv = e.detail.iv;
    data.encryptedData = e.detail.encryptedData;
    data.session_key = wx.getStorageSync('session_key');
    console.log(app.globalData.openid);
    // wx.getStorageSync('user_new')
    data.open_id = wx.getStorageSync('user_new');
    var _this=this;
    if (e.detail.errMsg == 'getPhoneNumber:ok'){
      wx.checkSession({
        success(res) {
          wx.request({
            url: 'https://xkcloude.hfhouse.com/routineclient/get_phone_number',

            method: 'post',

            headers: {
              'Content-Type': 'application/json'
            },

            dataType: 'json',

            data: data,

            success: function (res) {
              console.log(res);
              _this.setData({
                // userInfo: e.detail.userInfo,
                hasUserInfo: true,
                isMain: true,
                flag: true,
                isPower: false,
              })

            },

            fail: function (err) {
              errFun(err);
            }
          })
        },
        fail(err) {
          wx.login({
            success: res => {
              data.session_key = wx.getStorageSync('session_key');
            }
          })
        }
      })
    }
    else{
      console.log('收取失败')
      wx.showModal({
        title: "警告",
        content:"若不授权获取您的手机号可能部分功能无法使用；若点击取消，后期还使用小程序需在【微信】——【小程序】—删掉【星房惠】，重新搜索授权才可使用。",
        showCancel: true,
        cancelText: "拒绝",
        cancelColor: "#000",
        confirmText: "返回授权",
        confirmColor: "#017AE6",
        success: function (res) {
          console.log(res)
        }
      })
    }
  },

  // 首页弹出框广告
  adv() {
    let that = this
    let siteId = wx.getStorageSync('cityCode')
    if (siteId > 0) {
      app.core('get', 'adv/index?siteId=' + siteId, {}, (res) => {
        if (res.data != null && res.data.photo_url != undefined && res.data.photo_url != '') {
          that.setData({
              popAdv: res.data,
              modalName: 'Image'
          })

          let time = new Date().getTime()
          // wx.setStorageSync('index.adv', (time + (1000 * 86400)))
          wx.setStorageSync('index.adv', (time + (1000 * 60 * 60)))

          setTimeout(function () {
            that.setData({
              modalName: ''
            })
          }, 3000)
        }
      })
    }

  },

  jumpAdv() {
    let val = this.data.popAdv

    this.setData({
      modalName: null
    })

      this._advJump(val)
  },

  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },

  hideModal(e) {
    this.setData({
      modalName: null
    })
  },

  advJump (e) {

      let swiperList = this.data.swiperList

      let val = swiperList[e.currentTarget.dataset.index]
       this._advJump(val)
  },

    _advJump(val) {
        if (val) {
            if ( val['app_id'] != undefined && val['app_id'] != null && val['app_id'] != '') {
                wx.navigateToMiniProgram({
                    appId: val['app_id'],
                    path: val['redirect_url'],
                    extraData: {},
                    envVersion: 'release',
                    success(res) {
                        console.log(res)
                        // 打开成功
                    },
                    fail(e) {
                        console.log(e)
                    }
                })
            } else if ( val['redirect_url'] != undefined && val['redirect_url'] != null && val['redirect_url'] != '') {

                let url = val['redirect_url']

                if (url.indexOf("/pages") == 0) {
                    wx.navigateTo({
                        url: url,
                    })
                } else if (url.indexOf("http") == 0) {
                    wx.navigateTo({
                        url: '/pages/webView/index?url='+ decodeURIComponent(url),
                    })
                }
            }

        }
    }

})
